package org.example.studentmanager.service.impl;

import org.example.studentmanager.dao.AdminDao;
import org.example.studentmanager.dao.UserDao;
import org.example.studentmanager.entity.Student;
import org.example.studentmanager.entity.Teacher;
import org.example.studentmanager.entity.User;
import org.example.studentmanager.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    private static final Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class);

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private UserDao userDao;

    @Override
    @Transactional
    public String registerUser(User user, Student student, Teacher teacher) {
        try {
            // 检查用户名是否已存在
            Integer userId = userDao.getUserIdByUsername(user.getUsername());
            if (userId != null) {
                return "注册失败：用户名已存在，请选择其他用户名。";
            }

            user.setCreatedAt(LocalDateTime.now());
            user.setUpdatedAt(LocalDateTime.now());
            adminDao.insertUser(user);

            // 获取插入用户后的 id
            userId = user.getId();
            if (userId == null) {
                logger.error("插入用户后未能获取有效的 user_id");
                return "注册失败：未能获取有效的用户 ID";
            }
            logger.info("新插入用户的 ID: {}", userId);

            if ("student".equals(user.getRole()) && student != null) {
                // 为 student 对象设置 user_id
                student.setUserId(userId);
                logger.info("学生对象设置的 user_id: {}", student.getUserId());
                adminDao.insertStudent(student);
            } else if ("teacher".equals(user.getRole()) && teacher != null) {
                teacher.setUserId(userId);
                adminDao.insertTeacher(teacher);
            }

            return "注册成功";
        } catch (Exception e) {
            logger.error("用户注册失败，用户信息: {}", user, e);
            if (e.getMessage().contains("Duplicate entry")) {
                return "用户名重复";
            }
            return "注册失败：" + e.getMessage();
        }
    }

    @Override
    public User getUserById(Integer id) {
        return adminDao.getUserById(id);
    }

    // 修改用户信息接口
    @Override
    public void updateUser(User user) {
        user.setUpdatedAt(LocalDateTime.now());
        adminDao.updateUser(user);
    }

    // 查询所有用户信息接口
    @Override
    public List<User> findAllUsers() {
        return adminDao.findAllUsers();
    }

    // 删除用户接口
//    @Override
//    public int deleteUser(Integer userId) {
//        return 0;
//    }

    @Override
    public List<User> findUsersByRealName(String name) {
        return adminDao.findUsersByRealName(name);
    }

    // 新增：根据姓名删除用户
    @Override
    public int deleteUserByName(String name) {
        return adminDao.deleteUserByName(name);
    }

    @Override
    @Transactional
    public int deleteUserById(Integer userId) {
        return adminDao.deleteUserById(userId);
    }
}





